package com.cuts.videoedit.helper

import android.graphics.Bitmap
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.widget.ImageView
import com.cuts.videoedit.bean.TargetBean
import com.cuts.videoedit.data.YuvQueue
import com.cuts.videoedit.util.MyUtils
import com.cuts.videoedit.util.VideoUtils
import com.cuts.videoedit.util.md5
import com.cuts.videoedit.util.notNull
import java.util.concurrent.ConcurrentHashMap

class IFFmpegCodecFrameHelper(var filePath:String, override var itemFrameForTime: Long):IAvFrameHelper,Runnable {
    var targetViewMap: ConcurrentHashMap<ImageView, TargetBean> = ConcurrentHashMap()
    //是否应该暂停 循环线程
    private var hasPause = false
    var yuvQueue: YuvQueue = YuvQueue()
    override var decodeFrameListener: DecodeFrameListener?=null
    var lastBitMap: Bitmap? = null
    private var diskCache:DiskCacheAssist? = null

    private val mainKey = md5(filePath)
    private var childThread:Thread? = null
    //是否停止解码线程
    private var isStop = false
    override var isPause = false
    override var isScrolling: Boolean=false
    //是初始化了recyclerView的Item
    private var isInitItem = false
    override fun init() {
        diskCache=DiskCacheAssist(TextUtils.concat(Environment.getExternalStorageDirectory().path,
            "/frameCache/",mainKey).toString(),1,1, 121)
        childThread = Thread(this)
        childThread!!.start()
    }

    override fun run() {
        var index = 0
        while (!isStop){
            if (yuvQueue.getQueueSize()==0){
                Thread.sleep(10)
                if (!isScrolling){
                    isPause = false
//                  kzgPlayer?.pauseGetPacket(false)
                }
                continue
            }
            if (isScrolling){
                Thread.sleep(10)
                continue
            }
            if (hasPause){
                Thread.sleep(10)
                continue
            }
            //遍历ImageView 匹配时间，转换yuv为bitmap
            hasPause = true
            index = 0
            run task@{
                MyUtils.sortHashMap(targetViewMap).forEach {
                    index++
                    if (isScrolling){
                        return@task
                    }

                    yuvQueue.getFirst().let { bean->
                        if ((it.value?.timeUs?.toDouble()!! >= bean?.timeUs!! && !it.value.isAddFrame) || !it.value.isAddFrame){
                            hasPause = false
                            yuvQueue.deQueue()?.apply {
                                if (((it.value.timeUs >= this.timeUs-20_000 && it.value.timeUs<=this.timeUs+20_000)
                                            || (this.timeUs-it.value.timeUs>=30_000) || (it.value.timeUs < 30_000 && this.timeUs > it.value.timeUs))
                                    && !it.value.isAddFrame){

                                    if (isScrolling){
                                        return@task
                                    }
                                    isPause = false
//                                    kzgPlayer?.pauseGetPacket(false)
                                    notNull(y,u,v){
                                        val bitmap=VideoUtils.rawByteArray2RGBABitmap2(VideoUtils.YUVToNv21(y!!,u!!,v!!),width,height,practicalWidth)
                                        val newBitmap=VideoUtils.compressBySampleSize(bitmap,60,60,true)
                                        if (isScrolling){
                                            return@task
                                        }

                                        newBitmap?.let { bp->
                                            lastBitMap = bp
                                            it.value.isAddFrame = true
                                            diskCache?.writeBitmap("${filePath}_${it.value.timeUs}",bp,{ bitmap
                                                Log.e("kzg","**************缓存一帧bitmap成功：${it.value.timeUs}")
                                            },{e ->
                                                Log.e("kzg","**************缓存一帧bitmap失败：${it.value.timeUs}")
                                            })
                                            it.key.post {
                                                it.key.setImageBitmap(bp);
                                                targetViewMap.forEach { mp ->
                                                    if (!mp.value.isAddFrame){
                                                        mp.key.setImageBitmap(lastBitMap);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }




                            }
                        }


                    }



                }
            }



        }
    }


    override fun loadAvFrame(view: ImageView, timeMs: Long) {
        targetViewMap[view] = targetViewMap[view]?:TargetBean()
        lastBitMap?.let {
            if (targetViewMap[view]?.isAddFrame==false){
                view.setImageBitmap(it)
            }
        }

        if (targetViewMap[view]?.getTimeUs()!=timeMs){
            targetViewMap[view]?.setTimeUs(timeMs);
            targetViewMap[view]?.isAddFrame=false;
            targetViewMap[view]?.setRemoveTag(false)
            hasPause = false
            diskCache?.asyncReadBitmap("${filePath}_${timeMs}",timeMs,{
                bp,us->
                if (targetViewMap[view]?.timeUs == us){
                    //Log.e("kzg","**************取一帧bitmap成功：${timeMs}")
                    bp?.let {
                        targetViewMap[view]?.isAddFrame = true
                        view.setImageBitmap(it)
                    }
                }
            },{
                Log.e("kzg","**************取一帧bitmap失败：${timeMs}")
            })
        }
        if (!isInitItem) {
            isInitItem = true
            isPause = false
//            kzgPlayer?.pauseGetPacket(false)
        }
    }
}